/**
 * Created by zhangguoyu on 16/5/5.
 */

var TempLogs = require('../models/logs/TempLogs');
var MapReduceBuilder = require('../db/MapReduceBuilder');
var BaseLogsResolver = require('./BaseLogsResolver');
var LogUtils = require('../utils/log/LogUtils');
var Utils = require('../utils/Utils');
var util = require('util');
var TempsApp = require('../models/temps/TempsApp');

var coreDate = require('./CoreData');

var AppLogsResolver = Utils.extend(function () {
  if (arguments.length) {
    this.$resolvedModel = arguments[0];
  }
}, BaseLogsResolver, TempLogs);

AppLogsResolver.prototype.prepareResolve = function (model) {
  return new MapReduceBuilder()
    .map(function () {
      var key = this.date + '|' + this.time.split(':')[0] + '|' + this.flavor + '|' + this.appPackage;
      var news = 0;
      if (this.isNewUser) {
        news = 1;
      }
      emit(key, {visited: 1, news: news, users: news})
    })
    .reduce(function (key, values) {
      var reduceRes = {
        visited: 0,
        news: 0,
        users: 0
      };
      values.forEach(function (item) {
        reduceRes.visited += item.visited;
        reduceRes.news += item.news;
        reduceRes.users += item.users;
      });
      return reduceRes;
    })
    .verbose()
    .query({'actionCode': '1000'})
    .out({ replace: TempsApp.$name.toLowerCase() + 's'})
    .create();
};

AppLogsResolver.prototype.onResolving = function (date, time, flavor, code, values) {
  coreDate.globalStat().global().incVisited(time, flavor, values.visited).incNewUsers(time, flavor, values.news);
  coreDate.globalStat().app(code).incVisited(time, flavor, values.visited).incNewUsers(time, flavor, values.news);
  coreDate.dayStat(date).global().incVisited(time, flavor, values.visited).incNewUsers(time, flavor, values.news);
  coreDate.dayStat(date).app(code).incVisited(time, flavor, values.visited).incNewUsers(time, flavor, values.news);
  this.parent().onResolving.call(this, date, time, flavor, code, values);
};

AppLogsResolver.prototype.onCompletion = function (resolvedResult) {
  this.parent().onCompletion.call(this, resolvedResult);
};

module.exports = AppLogsResolver;